package study.nosql.redis.support.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import study.nosql.redis.support.serializer.FastjsonRedisSerializer;

/**
 * （1）RedisTemplate<K, V> 模板类在操作 redis 时，默认使用 JdkSerializationRedisSerializer 来进行序列化
 * （2）主要是四个序列化的配置：key、value、hashkey、hashvalue
 */
@Slf4j
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        //
        RedisTemplate<String, Object> template = new RedisTemplate();
        template.setConnectionFactory(factory);

        //序列化器
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer jacksonSerializer = new GenericJackson2JsonRedisSerializer();

        //序列化配置
        //key
        template.setKeySerializer(stringSerializer);
        template.setHashKeySerializer(stringSerializer);
        //value
        template.setValueSerializer(jacksonSerializer);
        template.setHashValueSerializer(jacksonSerializer);

        //
        template.setEnableTransactionSupport(false);
        template.afterPropertiesSet();
        return template;
    }

    //    @Bean
    public RedisSerializer<Object> fastJson2JsonRedisSerializer() {
        return new FastjsonRedisSerializer<>(Object.class);
    }
}
